/*
 *
 * Licensed under the Apache License, Version 2.0 (the "License"); you may not use this file except
 * in compliance with the License. You may obtain a copy of the License at
 *
 * http://www.apache.org/licenses/LICENSE-2.0
 *
 * Unless required by applicable law or agreed to in writing, software distributed under the License
 * is distributed on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express
 * or implied. See the License for the specific language governing permissions and limitations under
 * the License.
 *
 * Copyright @2008 the original author or authors.
 */
package com.bluestone.core;

import java.awt.image.BufferedImage;
import java.io.File;
import java.io.IOException;

import javax.imageio.ImageIO;

import com.bluestone.util.Util;

/**
 * @author <a href="mailto:ming7655@gmail.com">Aaron</a>
 * 
 */
public class CompareImageAction extends Action {
	private String defaultImagePath="C:\\bluestone\\images\\";

	/**
	 * 
	 * @param type
	 * @param target String that defines the target image path.
	 * @param value String that defines the source image path.
	 * @param delay
	 * @param offset
	 */
	public CompareImageAction(String type, String target, String value,
			String delay, String offset) {
		super(type, target, value, delay, offset);
	}

	/**
	 * Compare the target image with the source image
	 * @return false if the target image is not equal with the source image
	 */
	public boolean execute() {
		if (!super.execute()){
			return false;
		}
		
		boolean isCompared = false;
		if(target.indexOf(":")<0){
			target=defaultImagePath+target;
		}
		Action saveAsAction = ActionFactory.createAction(
				ActionFactory.SAVEASACTION, null, target, null, null);
		if (saveAsAction.execute()) {
			isCompared = compareImage(target, value);
		}
		if (delay != null && delay.length() > 0) {
			robot.delay(Util.getDelayTime(Integer.parseInt(delay)));
		} else {
			robot.delay(Util.getDelayTime(Util.COMPAREIMAGEDELAY));
		}
		return isCompared;
	}

	private boolean compareImage(String image1, String image2) {
		try {
			BufferedImage bi1 = ImageIO.read(new File(image1));
			BufferedImage bi2 = ImageIO.read(new File(image2));
			int h1 = bi1.getHeight();
			int w1 = bi1.getWidth();
			int h2 = bi2.getHeight();
			int w2 = bi2.getWidth();
			if (h1 != h2 || w1 != w2) {
				return false;
			}
			for (int i = 0; i < w1; i++) {
				for (int j = 0; j < h1; j++) {
					int biRGB1 = bi1.getRGB(i, j);
					int biRGB2 = bi2.getRGB(i, j);
					if (biRGB1 != biRGB2) {
						return false;
					}
				}
			}
		} catch (IOException e) {
			Util.error(e);
			return false;
		}
		return true;
	}

}
